package com.an.pay.task;

import com.an.pay.client.AliPayClient;
import com.an.pay.entity.OrderInfo;
import com.an.pay.enums.AliPayTradeState;
import com.an.pay.enums.OrderStatus;
import com.an.pay.enums.PayType;
import com.an.pay.service.OrderInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class AliPayTask {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private AliPayClient aliPayClient;

    @Scheduled(cron = "0/60 * * * * ?")
    public void CheckOrderStatus(){
        Gson gson = new Gson();
        log.info("进入支付宝CheckOrderStatus");
        List<OrderInfo> orderInfoList = orderInfoService.getNoPayOrderByDuration(1, PayType.ALIPAY.getType());
        for (OrderInfo orderInfo : orderInfoList) {
            // 查询当前订单状态，返回数据
            String body = aliPayClient.queryOrder(orderInfo.getOrderNo());
            log.info("orderStatus==={}",body);
            Map<String,Object> data = gson.fromJson(body, Map.class);
            Map<String,String>  map= (Map<String, String>) data.get("alipay_trade_query_response");
            String trade_status = map.get("trade_status");
            log.info("map=={}",map);
            log.info("trade_status=={}",trade_status);
            if(AliPayTradeState.SUCCESS.getType().equals(trade_status)){
                //支付成功，更新订单状态
                log.info("支付成功，更新订单状态");
                OrderInfo order = new OrderInfo();
                order.setOrderStatus(OrderStatus.SUCCESS.getType());
                orderInfoService.update(order,new QueryWrapper<OrderInfo>().eq("order_no",orderInfo.getOrderNo()));
            }else if (AliPayTradeState.CLOSED.getType().equals(trade_status)){
                //订单关闭或退款
                log.info("订单关闭或退款，更新状态");
                OrderInfo order = new OrderInfo();
                order.setOrderStatus(OrderStatus.CLOSED.getType());
                orderInfoService.update(order,new QueryWrapper<OrderInfo>().eq("order_no",orderInfo.getOrderNo()));
            }

        }

    }
}
